package com.jrx.anytxn.param.job.bactchlimitadjust.step;

import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.config.AdjustLimitFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.BtLimitAdjustInfo;
import com.jrx.anytxn.param.entity.TlBatchAdjustLimit;
import com.jrx.anytxn.param.job.bactchlimitadjust.bean.LimitAdjustBean;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 批量调额processor
 *
 * @author : zhenghaopu
 * 2020/1/6
 */
@Service
public class BatchLimitAdjustStep1Processor implements ItemProcessor<TlBatchAdjustLimit, LimitAdjustBean> {

    private final Logger logger = LoggerFactory.getLogger(BatchLimitAdjustStep1Processor.class);

    @Autowired
    private AdjustLimitFileConfig adjustLimitFileConfig;

    @Autowired
    private ISegmentService segmentService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public LimitAdjustBean process(TlBatchAdjustLimit tlBatchAdjustLimit) throws Exception {
        LimitAdjustBean limitAdjustBean = new LimitAdjustBean();
        List<TlBatchAdjustLimit> tlBatchAdjustLimits = new ArrayList<>();

        if(null == tlBatchAdjustLimit){
            return null;
        }

        List<BtLimitAdjustInfo> btLimitAdjustInfoList = readCsvFile(tlBatchAdjustLimit,adjustLimitFileConfig.getBasePath());

        List<BtLimitAdjustInfo> insertList = new ArrayList<>();
        for(BtLimitAdjustInfo btLimitAdjustInfo : btLimitAdjustInfoList){
            try {
                //发送调额消息
                SendResult sendResult = rocketMQTemplate.syncSend(Constant.MQ_BATCH_LIMIT_ADJUST_TOPIC,
                        JsonUtils.obj2jsonIgnoreNull(btLimitAdjustInfo));
                //MQ发送是否成功
                if(SendStatus.SEND_OK  != sendResult.getSendStatus()){
                    btLimitAdjustInfo.setMqStatus(Constant.MQ_SATTUS_2);
                }
            }catch (Exception e){
                logger.error(ErrorMsgConstant.MQ_SEND_ERROR,e);
                btLimitAdjustInfo.setMqStatus(Constant.MQ_SATTUS_2);
            }

            insertList.add(btLimitAdjustInfo);
        }
        tlBatchAdjustLimit.setHandleStatus(Constant.HANDLE_STATUS_1);
        tlBatchAdjustLimits.add(tlBatchAdjustLimit);

        limitAdjustBean.setBtLimitAdjustInfoList(insertList);
        limitAdjustBean.setTlBatchAdjustLimitList(tlBatchAdjustLimits);


        return limitAdjustBean;
    }

    /**
     * 补充批量调额信息
     * @param btLimitAdjustInfo 批量调额新西
     * @throws SegmentException 主键生成错误
     */
    private void buildBtLimitAdjustInfo(BtLimitAdjustInfo btLimitAdjustInfo) throws SegmentException {



    }

    /**
     * 读取调额文件
     * @param tlBatchAdjustLimit
     * @return
     */
    private List<BtLimitAdjustInfo> readCsvFile(TlBatchAdjustLimit tlBatchAdjustLimit,String filePath) {
        List<BtLimitAdjustInfo> btLimitAdjustInfoList = new ArrayList<>();

        String basePath = filePath + tlBatchAdjustLimit.getFilePath();
        File csv = new File(basePath);
        if (csv.isFile() && csv.exists()) {
            try (BufferedReader br = new BufferedReader(new FileReader(csv))) {
                while (br.ready()) {
                    String line = br.readLine();
                    List<String> content = Arrays.asList(line.split(","));
                    //过滤掉第一行
                    if(content.get(0).equals("customerId")){
                        continue;
                    }
                    BtLimitAdjustInfo btLimitAdjustInfo = new BtLimitAdjustInfo();
                    btLimitAdjustInfo.setTenantId(tlBatchAdjustLimit.getTenantId());
                    btLimitAdjustInfo.setCustomerId(content.get(0));
                    DecimalFormat g1=new DecimalFormat("0000");
                    String orgId = g1.format(Integer.valueOf(content.get(1)));
                    btLimitAdjustInfo.setOrganizationId(orgId);
                    btLimitAdjustInfo.setLimitId(content.get(2));
                    btLimitAdjustInfo.setTemplateId(content.get(3));
                    btLimitAdjustInfo.setLimitPerm(new BigDecimal(content.get(4)));
                    btLimitAdjustInfo.setChannel(content.get(5));
                    btLimitAdjustInfo.setDataSource(content.get(6));
                    btLimitAdjustInfo.setUpdateBy(tlBatchAdjustLimit.getUpdateBy());

                    btLimitAdjustInfo.setId(segmentService.getId(Constant.BT_LIMIT_ADJUST_INFO));
                    btLimitAdjustInfo.setSeqNo(SeqUtils.getSNByLength(32));//流水号
                    btLimitAdjustInfo.setMqStatus(Constant.MQ_SATTUS_1);
                    btLimitAdjustInfo.setAdjustStatus(Constant.ADJUST_SATTUS_0);//调额状态
                    btLimitAdjustInfo.setRecordVersionNumber(Constant.VERSION_NUMBER);//版本号
                    btLimitAdjustInfo.setBatchId(tlBatchAdjustLimit.getBatchId());//批次号

                    btLimitAdjustInfoList.add(btLimitAdjustInfo);
                }
            } catch (Exception e) {
                logger.error("读取批量调额文件失败,",e);
            }
        }
        return btLimitAdjustInfoList;
    }
}
